import { saveAs } from 'file-saver'
import { Workbook } from 'exceljs'

export function saveWorkbook(workbook: Workbook, fileName: string) {
  // 导出文件
  workbook.xlsx.writeBuffer().then((data => {
    const blob = new Blob([data], { type: '' })
    saveAs(blob, fileName)
  }))
}

const DEFAULT_COLUMN_WIDTH = 40

// 根据 antd 的 column 生成 exceljs 的 column
export function generateHeaders(columns: any[]) {
  return columns?.map(col => {
    const obj: any = {
      // 显示的 name
      header: col.title,
      // 用于数据匹配的 key
      key: col.dataIndex,
      // 列宽
      width: col.width / 4 || DEFAULT_COLUMN_WIDTH,
    }
    return obj
  })
}
import * as ExcelJs from 'exceljs'
// columns: 表头
// list: 导出的列表
// sheetName:表格sheet名字
// fileName: 表格文件的名字
// rowSpan 是否合并单元格
// className: 合并单元格的名称
export const onExportBasicExcel = (columns:any, list:any, sheetName:any, fileName?:any, rowSpan = false, className?:any)=> {

  // 创建工作簿
  const workbook = new ExcelJs.Workbook()
  // 添加sheet
  const worksheet = workbook.addWorksheet(sheetName)
  // 设置 sheet 的默认行高
  worksheet.properties.defaultRowHeight = 13.5
  // 设置列
  worksheet.columns = generateHeaders(columns)

  //导出后合并单元格  record.class合并的那个类名
  if (rowSpan){
    // 添加行
    worksheet.addRows(list).forEach((va)=>{
      va.alignment = { vertical: 'middle' }
    })
    const mergeCells:any = []
    let currentRowIndex = 2
    let prevRecord:any = null
    list.forEach((record:any) => {
      if (prevRecord && prevRecord[className] === record[className]) {
        const range = mergeCells[mergeCells.length - 1]
        range.bottom += 1
      } else {
        const range = {
          left: 1,
          top: currentRowIndex,
          right: 1, // 假定数据表格有 5 列，需要修改为实际列数
          bottom: currentRowIndex,
        }
        mergeCells.push(range)
      }
      currentRowIndex += 1
      prevRecord = record
    })
    // 合并单元格
    mergeCells.forEach((range:any) => {
      worksheet.mergeCells(range.top, range.left, range.bottom, range.right)
    })
  } else {
    // 添加行
    worksheet.addRows(list)
  }
  // 获取表头范围
  const headerRange = worksheet.getRow(1).cellCount

  // 添加边框到表头
  worksheet.getRow(1).border = {
    top: { style: 'thin' },
    left: { style: 'thin' },
    bottom: { style: 'thin' },
    right: { style: 'thin' },
  }

  // 添加边框到表格内容
  for (let r = 2; r <= worksheet.rowCount; r++) {
    for (let c = 1; c <= headerRange; c++) {
      const cell = worksheet.getCell(r, c)
      cell.border = {
        top: { style: 'thin' },
        left: { style: 'thin' },
        bottom: { style: 'thin' },
        right: { style: 'thin' },
      }
    }
  }
  // worksheet.mergeCells(2, 2, 2, 1)
  // 设置表头颜色
  // worksheet.getRow(1).fill = {
  //   type: 'pattern',
  //   pattern: 'solid',
  //   fgColor: { argb: 'dff8ff' },
  // }
  // worksheet.getRow(1).font = { name: '宋体', size: 12, bold: true }
  // 导出excel
  saveWorkbook(workbook, `${fileName}.xlsx`)
}
